var category = "";
var eventData;
var doctor;
var starts;
var ends;
starts = $("#startTimeValue").val().substring(0, 10) + " 00:00:00";
ends = $("#endTimeValue").val().substring(0, 10) + " 23:59:59";
$(function() {
    eventData = $("#startTimeValue").val() + "," + $("#endTimeValue").val();
    getListInfo();
    $.ajax({
        url: Feng.ctxPath + "/consultant/getDoctor",
        type: "get",
        success: function(data) {
            var txt = '<option value="未指定医生">未指定医生</option>';
            for (var i = 0; i < data.length; i++) {
                txt += '<option value="' + data[i].doctor + '">' + data[i].doctor + '</option>'
            }
            document.getElementById('doctor').innerHTML = txt;
            var seleteDoctorValue = $('#doctorValue').val();
            if (seleteDoctorValue != "") {
                $("#doctor option[value=" + seleteDoctorValue + "]").attr("selected", "selected")
            }
        },
        error: function(data) {
            alert('没有权限，请联系管理员!')
        }
    });
    $.post(Feng.ctxPath + "/tc/getLists", function(data) {
        var txt = '<option value="待定TC">待定TC</option>';
        for (var i = 0; i < data.length; i++) {
            txt += '<option value="' + data[i].tcName + '">' + data[i].tcName + '</option>'
        }
        document.getElementById('fieldTc').innerHTML = txt;
        var seletetcName = $('#tcNameValue').val();
        if (seletetcName != "") {
            $("#fieldTc option[value=" + seletetcName + "]").attr("selected", "selected")
        }
    }, "json");
    $.post(Feng.ctxPath + "/payService/getDepartment", function(data) {
        var txt = '<option value="待定">待定</option>';
        for (var i = 0; i < data.length; i++) {
            txt += '<option value="' + data[i].department + '">' + data[i].department + '</option>'
        }
        document.getElementById('treatmentUnit').innerHTML = txt;
        var treatmentUnit2 = $('#treatmentUnitValue').val();
        if (treatmentUnit2 != "") {
            $("#treatmentUnit option[value=" + treatmentUnit2 + "]").attr("selected", "selected")
        }
    }, "json");
    $('#calendars').fullCalendar({
        header: {
            left: '',
            center: '',
            right: ''
        },
        defaultView: 'agendaDay',
        allDaySlot: false,
        selectable: true,
        selectHelper: true,
        editable: false,
        eventLimit: true,
        nowIndicator: true,
        minTime: "08:00:00",
        maxTime: "20:00:00",
        titleFormat: 'YYYY-MM-DD',
        slotDuration: "00:15:00",
        slotLabelFormat: 'HH',
        slotLabelInterval: "00:60:00",
        slotLabelFormats: 'mm',
        slotLabelIntervals: "00:15:00",
        selectMinDistance: 30,
        defaultDate: $("#startTimeValue").val().substring(0, 10),
        height: window.innerHeight - 88,
        select: function(startDate, endDate, jsEvent, view, resource) {
            var start = startDate.format('YYYY-MM-DD HH:mm:ss');
            var end = endDate.format('YYYY-MM-DD HH:mm:ss');
            var start1 = new Date(start);
            var end1 = new Date(end);
            var continued = parseInt(end1 - start1) / 1000 / 60;
            $("#startTime").val(start);
            $("#duration").val(continued);
            var docName = document.getElementById("doctorValue").value;
            eventData = start + "," + end + "," + docName
        },
        timeFormat: 'H:mm',
        slotEventOverlap: false,
        schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
        dragRevertDuration: 200,
        unselectAuto: false,
        aspectRatio: 0.6,
        events: function(start, end, timezone, callback) {
            start = starts;
            end = ends;
            doctor = document.getElementById('doctorValue').value;
            var timeSlot = start + "," + end + "," + doctor;
            $.ajax({
                url: Feng.ctxPath + '/doctorLooked/getDataListByDoctor/' + timeSlot,
                dataType: 'json',
                type: 'POST',
                success: function(data) {
                    var events = [];
                    $.each(data, function(key, value) {
                        var obj = {
                            id: value.customerId,
                            title: value.appointmentPayService,
                            start: new Date(Date.parse(value.startTime)),
                            end: new Date(Date.parse(value.endTime)),
                            customerName: value.customerName,
                            resourceId: value.id,
                            arrivalStatus: value.arrivalStatus,
                            accountarrears: value.accountarrears
                        };
                        if (value.arrivalStatus == '1') {
                            obj.backgroundColor = "#4099ff";
                            obj.borderColor = "#4099ff"
                        } else if (value.arrivalStatus == '2') {
                            obj.backgroundColor = "#10428b";
                            obj.borderColor = "#10428b"
                        } else if (value.arrivalStatus == '3') {
                            obj.backgroundColor = "#ffba40";
                            obj.borderColor = "#ffba40"
                        } else if (value.arrivalStatus == '4') {
                            obj.backgroundColor = "#2dc87e";
                            obj.borderColor = "#2dc87e"
                        } else if (value.arrivalStatus == '5') {
                            obj.backgroundColor = "#61b740";
                            obj.borderColor = "#61b740"
                        } else if (value.arrivalStatus == '6') {
                            obj.backgroundColor = "#017cdc";
                            obj.borderColor = "#017cdc"
                        } else if (value.arrivalStatus == '7') {
                            obj.backgroundColor = "gray";
                            obj.borderColor = "gray"
                        }
                        events.push(obj)
                    });
                    callback(events)
                }
            })
        },
        eventRender: function(calEvent, element, view) {
            if (calEvent.customerName == "" || calEvent.customerName == null) {
                element.prepend("<div class='myfc-title'><span>新建预约</span></div>")
            }
        },
        eventAfterRender: function(calEvent, element, view) {
            var data3 = parseInt(calEvent.end._d - calEvent.start._d) / 1000 / 60;
            if (element[0].clientWidth < 24) {
                element[0].innerHTML = ""
            } else if (element[0].clientWidth >= 24 && element[0].clientWidth < 45) {
                element[0].innerHTML = "";
                element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
            } else {
                if (calEvent.accountarrears != 0) {
                    if (data3 < 61) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarks + "</div><div style='position: absolute;right: 2px;top: 1px;color: white;background: red;padding: 0 2px;border: 1px solid white;border-radius: 50%;font-size: 0.5em'>欠</div>")
                    }
                } else {
                    if (data3 < 61) {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div>")
                    } else {
                        element.prepend("<div class='myfc-title'><span style='font-size: 15px;font-weight: bold;letter-spacing: 2px;'>" + calEvent.customerName + "</span></div><div style='position: absolute;bottom: 5px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;'>" + calEvent.remarks + "</div>")
                    }
                }
            }
        }
    });
    preloading()
});

function getListInfo() {
    $.ajax({
        url: Feng.ctxPath + "/doctorLooked/getListInfo",
        data: {
            "projectCategory": $("#projectCategory").val()
        },
        type: "POST",
        success: function(data) {
            var text = '';
            for (var i = 0; i < data.length; i++) {
                text += '<div><label style="font-weight: 500;margin:0;"><input type="checkbox" name="about" style="vertical-align: middle;margin: 0 8px 0;" value="' + data[i].projectName + '" >' + data[i].projectName + '</label></div>'
            }
            $("#projectType").html(text);
            var payService = $("#payService").val();
            if (payService != "" && payService != null) {
                var arr = payService.split(",");
                for (var i = 0; i < arr.length; i++) {
                    $("input[type='checkbox'][name='about'][value=" + arr[i] + "]").attr('checked', true)
                }
            }
        }
    })
}

function addSet() {
    var index = layer.open({
        type: 2,
        title: '预约项目设置',
        area: ['80%', '80%'],
        fix: true,
        maxmin: true,
        content: Feng.ctxPath + '/doctorLooked/add_project'
    });
    this.layerIndex = index
}
checkDate = function() {
    var value = $("#startTime").val();
    doctor = document.getElementById('doctorValue').value;
    starts = value.substring(0, 10) + " 00:00:00";
    ends = value.substring(0, 10) + " 23:59:59";
    $("#startTimeValue").val(starts);
    $('#calendars').fullCalendar('gotoDate', value.substring(0, 10));
    $('#calendars').fullCalendar('refetchEvents');
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/doctorLooked/getDoctorStatus",
        data: {
            "doctor": doctor,
            "value": value
        },
        dataType: "json",
        success: function(data) {
            if (data == 2) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#eeeeee");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "none",
                    "cursor": "not-allowed"
                })
            } else if (data == 1) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#FFFFFF");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "",
                    "cursor": ""
                });
                viewUpdate()
            }
        }
    })
};
$("#startTime").on('input', function() {
    if ($("#startTime").val().length == 19) {
        viewUpdate()
    }
});

function preloading() {
    var start = $("#startTimeValue").val();
    var end = $("#endTimeValue").val();
    var startOne = start.substring(0, 19);
    var endOne = end.substring(0, 19);
    var startTwo = new Date(startOne);
    var endTwo = new Date(endOne);
    var continued = parseInt(endTwo - startTwo) / 1000 / 60;
    $("#duration").val(continued);
    $('#calendars').fullCalendar('select', startOne, endOne, true)
}

function continued(obj) {
    var time = $("#duration").val();
    if (obj == "-") {
        if (time == 0) {
            $("#duration").val(0);
            viewUpdate()
        } else {
            $("#duration").val(parseInt(time) - 15);
            viewUpdate()
        }
    } else if (obj == "+") {
        $("#duration").val(parseInt(time) + 15);
        viewUpdate()
    }
}

function viewUpdate() {
    var start = $("#startTime").val();
    var date = new Date(start.replace("-", "/"));
    date.setMinutes(date.getMinutes() + parseInt($("#duration").val()), date.getSeconds(), 0);
    var ends = new Date(date);
    var currentYear = ends.getFullYear();
    var currentMonth = ends.getMonth() + 1;
    var currentDay = ends.getDate();
    var currentHours = ends.getHours();
    var currentMinutes = ends.getMinutes();
    if (currentMonth < 10) currentMonth = "0" + currentMonth;
    if (currentDay < 10) currentDay = "0" + currentDay;
    if (currentHours < 10) currentHours = "0" + currentHours;
    if (currentMinutes < 10) currentMinutes = "0" + currentMinutes;
    var end = currentYear + "-" + currentMonth + '-' + currentDay + ' ' + currentHours + ':' + currentMinutes;
    $('#calendars').fullCalendar('select', start, end, true)
}

function refreshChange() {
    document.getElementById('doctorValue').value = $("#doctor").val();
    var doctor = document.getElementById('doctorValue').value;
    var value = $("#startTimeValue").val().substring(0, 10);
    $('#calendars').fullCalendar('refetchEvents');
    $.ajax({
        type: "POST",
        url: Feng.ctxPath + "/doctorLooked/getDoctorStatus",
        data: {
            "doctor": doctor,
            "value": value
        },
        dataType: "json",
        success: function(data) {
            if (data == 2) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#eeeeee");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "none",
                    "cursor": "not-allowed"
                })
            } else if (data == 1) {
                $('#calendars .fc-time-grid td.fc-day').css("background", "#FFFFFF");
                $('#calendars .fc-time-grid').css({
                    "pointer-events": "",
                    "cursor": ""
                })
            }
        }
    })
}

function updateSubmission() {
    var startTimeValue = eventData.split(",")[0];
    var endTimeValue = eventData.split(",")[1];
    var customerPhone = document.getElementById("customerPhone").innerHTML;
    var fieldTc = document.getElementById("fieldTc").value;
    var doctor = document.getElementById("doctor").value;
    var remarks = document.getElementById("remarks").value;
    var reservationsId = document.getElementById("reservationsId").value;
    var customerId = document.getElementById("customerId").value;
    var check = $("input[type='checkbox']:checked");
    var projectData = "";
    for (var i = 0; i < check.length; i++) {
        projectData += $(check[i]).val() + ","
    }
    var tiem = new Date();
    var YY = tiem.getFullYear();
    var MM = tiem.getMonth() + 1;
    var DD = tiem.getDate();
    if (MM < 10) {
        MM = "0" + MM
    }
    if (DD < 10) {
        DD = "0" + DD
    }
    var weekEnd = startTimeValue.split(" ")[0] + " 20:00:00";
    if (startTimeValue > weekEnd) {
        alert("预约时间不在医生工作时间内！");
        return
    }
    $.ajax({
        url: Feng.ctxPath + "/customer/updateReservation",
        type: "post",
        data: {
            "reservationsId": reservationsId,
            "startTimeValue": startTimeValue,
            "endTimeValue": endTimeValue,
            "customerPhone": customerPhone,
            "customerId": customerId,
            "projectData": projectData,
            "fieldTc": fieldTc,
            "doctor": doctor,
            "remarks": remarks
        },
        success: function(data) {
            Feng.success('修改成功!');
            parent.location.href = Feng.ctxPath + '/consultantTwo/consultantToDetailByTab/' + customerId + '/5/0';
            parent.layer.close(parent.layer.getFrameIndex(window.name))
        },
        error: function(data) {
            alert('预约失败!')
        }
    })
}